//
//	 ______    ______    ______    
//	/\  __ \  /\  ___\  /\  ___\   
//	\ \  __<  \ \  __\_ \ \  __\_ 
//	 \ \_____\ \ \_____\ \ \_____\ 
//	  \/_____/  \/_____/  \/_____/ 
//
//	Powered by BeeFramework
//
//
//  AddContactBoard.m
//  iHeima
//
//  Created by he chao on 6/10/14.
//  Copyright (c) 2014 leon. All rights reserved.
//

#import "AddContactBoard.h"

#pragma mark -

@interface AddContactBoard()
{
	//<#@private var#>
    
    NSInteger _cellIndex;
    
    NSMutableString* _myStrMobile;
}
@end

@implementation AddContactBoard

- (void)load
{
}

- (void)unload
{
}

#pragma mark - Signal

ON_CREATE_VIEWS( signal )
{
    self.title = @"添加好友";
    [self showBarButton:BeeUINavigationBar.LEFT image:IMAGESTRING(@"navi_back")];
    [self showNaviBar];
    [self loadContent];
    [self GetUserAddressBook];
}

ON_DELETE_VIEWS( signal )
{
}

ON_LAYOUT_VIEWS( signal )
{
}

ON_WILL_APPEAR( signal )
{
}

ON_DID_APPEAR( signal )
{
}

ON_WILL_DISAPPEAR( signal )
{
}

ON_DID_DISAPPEAR( signal )
{
}

ON_SIGNAL3( BeeUINavigationBar, LEFT_TOUCHED, signal )
{
    [self.stack popBoardAnimated:YES];
}

ON_SIGNAL3( BeeUINavigationBar, RIGHT_TOUCHED, signal )
{
}

- (void)loadContent{
    myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.viewWidth, self.viewHeight-(IOS7_OR_LATER?64:44))];
    myTableView.delegate = self;
    myTableView.dataSource = self;
    [self.view addSubview:myTableView];
}

//获取通讯录
-(void)GetUserAddressBook
{
    //获取通讯录权限
    ABAddressBookRef ab = NULL;
    // ABAddressBookCreateWithOptions is iOS 6 and up.
    if (&ABAddressBookCreateWithOptions) {
        CFErrorRef error = nil;
        ab = ABAddressBookCreateWithOptions(NULL, &error);
        
        if (error) { NSLog(@"%@", error); }
    }
    if (ab == NULL) {
        ab = ABAddressBookCreate();
    }
    if (ab) {
        // ABAddressBookRequestAccessWithCompletion is iOS 6 and up. 适配IOS6以上版本
        if (&ABAddressBookRequestAccessWithCompletion) {
            ABAddressBookRequestAccessWithCompletion(ab,
                                                     ^(bool granted, CFErrorRef error) {
                                                         if (granted) {
                                                             // constructInThread: will CFRelease ab.
                                                             [NSThread detachNewThreadSelector:@selector(constructInThread:)
                                                                                      toTarget:self
                                                                                    withObject:CFBridgingRelease(ab)];
                                                         } else {
                                                             //                                                             CFRelease(ab);
                                                             // Ignore the error
                                                         }
                                                     });
        } else {
            // constructInThread: will CFRelease ab.
            [NSThread detachNewThreadSelector:@selector(constructInThread:)
                                     toTarget:self
                                   withObject:CFBridgingRelease(ab)];
        }
    }
}
//获取到addressbook的权限
-(void)constructInThread:(ABAddressBookRef) ab
{
    NSLog(@"we got the access right");
    CFArrayRef results = ABAddressBookCopyArrayOfAllPeople(ab);
    NSMutableArray* contactArray = [[NSMutableArray alloc]init];
    for(int i = 0; i < CFArrayGetCount(results); i++)
    {
        ABRecordRef person = CFArrayGetValueAtIndex(results, i);
        
        NSString *strName;
        if (ABRecordCopyValue(person, kABPersonLastNameProperty)&&(ABRecordCopyValue(person, kABPersonFirstNameProperty))== nil) {
            strName = (__bridge NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
        }else if (ABRecordCopyValue(person, kABPersonLastNameProperty) == nil&&(ABRecordCopyValue(person, kABPersonFirstNameProperty))){
            strName = (__bridge NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
        }else if (ABRecordCopyValue(person, kABPersonLastNameProperty)&&(ABRecordCopyValue(person, kABPersonFirstNameProperty))){
            
            NSString *first =(__bridge NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
            NSString *last = (__bridge NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
            strName = [NSString stringWithFormat:@"%@%@",last,first];
        }
        
        
        //读取电话信息，和emial类似，也分为工作电话，家庭电话，工作传真，家庭传真。。。。
        
        ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
        
        NSString *strPhone;
        if ((phone != nil)&&ABMultiValueGetCount(phone)>0) {
            
            for (int m = 0; m < ABMultiValueGetCount(phone); m++) {
                NSString * aPhone = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phone, m);
                //NSString * aLabel = (__bridge NSString *)ABMultiValueCopyLabelAtIndex(phone, m);
                
                strPhone = aPhone;
                
                //                if ([aLabel isEqualToString:@"_$!<Mobile>!$_"]) {
                //                    strPhone = aPhone;
                //                    //iphoneContact.contactMobile= aPhone;
                //
                //                }
                //
                //                if ([aLabel isEqualToString:@"_$!<WorkFAX>!$_"]) {
                //                    strPhone = aPhone;
                //                    //iphoneContact.contactFax = aPhone;
                //                }
                //
                //                if ([aLabel isEqualToString:@"_$!<Work>!$_"]) {
                //                    strPhone = aPhone;
                //                    //iphoneContact.contactTelephone= aPhone;
                //                }
            }
        }
        if (strPhone && strName) {
            strPhone = [strPhone stringByReplacingOccurrencesOfString:@"+86" withString:@""];
            strPhone = [strPhone stringByReplacingOccurrencesOfString:@"+" withString:@""];
            strPhone = [strPhone stringByReplacingOccurrencesOfString:@" " withString:@""];
            strPhone = [strPhone stringByReplacingOccurrencesOfString:@"(" withString:@""];
            strPhone = [strPhone stringByReplacingOccurrencesOfString:@")" withString:@""];
            strPhone = [strPhone stringByReplacingOccurrencesOfString:@"-" withString:@""];
            
            //NSDictionary *dict = @{@"name": strName,@"phone":strPhone};
            NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:strName,@"name",strPhone,@"phone", nil];
            [contactArray addObject:dict];
        }
        
        /*
         
         //姓
         NSString *firstName = (NSString*)CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty));
         //姓音标
         //        NSString *firstNamePhonetic = (NSString*)CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNamePhoneticProperty));
         //名
         NSString *lastname = (NSString*)CFBridgingRelease(ABRecordCopyValue(person, kABPersonLastNameProperty));
         //名音标
         //        NSString *lastnamePhonetic = (NSString*)CFBridgingRelease(ABRecordCopyValue(person, kABPersonLastNamePhoneticProperty));
         //公司
         NSString *Organization = (NSString*)CFBridgingRelease(ABRecordCopyValue(person, kABPersonOrganizationProperty));
         //读取jobtitle工作
         //        NSString *jobtitle = (NSString*)CFBridgingRelease(ABRecordCopyValue(person, kABPersonJobTitleProperty));
         //读取department部门
         NSString *department = (NSString*)CFBridgingRelease(ABRecordCopyValue(person, kABPersonDepartmentProperty));
         //读取birthday生日
         NSDate *birthday = (NSDate*)CFBridgingRelease(ABRecordCopyValue(person, kABPersonBirthdayProperty));
         //读取nickname呢称
         double birthdayString = [birthday timeIntervalSince1970];
         NSString *nickname = (NSString*)CFBridgingRelease(ABRecordCopyValue(person, kABPersonNicknameProperty));
         //读取电话多值
         NSString* phoneString = @"";
         ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);*/
    }
    
    [self performSelectorOnMainThread:@selector(uploadContacts:) withObject:contactArray waitUntilDone:NO];
}

- (void)uploadContacts:(NSMutableArray *)contactArray{
    arrayUser = [contactArray mutableCopy];
    if (contactArray.count==0) {
        [[BeeUITipsCenter sharedInstance] presentMessageTips:@"您的通讯录内未有任何联系人"];
        return;
    }
    NSMutableString *strMobile = [[NSMutableString alloc] init];
    for (int i = 0; i < contactArray.count; i++) {
        [strMobile appendString:contactArray[i][@"phone"]];
        if (i < contactArray.count-1) {
            [strMobile appendString:@","];
        }
    }
//    BeeHTTPRequest* req = [self POST:[NSString stringWithFormat:@"%@/apiuser/matchcontact",kBaseUrl]].PARAM(@"uid",kUserInfo[@"uid"]).PARAM(@"mobilestr",strMobile);
//    
//    req.tag = 7777;
    
    
    [self matchContactWithStrMobile:strMobile];
}

- (void)matchContactWithStrMobile:(NSMutableString*)strMobile{
    
    BeeHTTPRequest* req = [self POST:[NSString stringWithFormat:@"%@/apiuser/matchcontact",kBaseUrl]].PARAM(@"uid",kUserInfo[@"uid"]).PARAM(@"mobilestr",strMobile);
    
    req.tag = 7777;
    
}



- (void)handleRequest:(BeeRequest *)request
{
    if(request.failed)
    {
        [[BeeUITipsCenter sharedInstance] dismissTips];
        NETWORK_ERROR
    }
    else if (request.succeed)
    {
        id json = [request.responseString mutableObjectFromJSONString];
        NSLog(@"%@",json);
        switch ([json[@"status"] intValue]) {
            case 1:
                
            {
                
                switch (request.tag) {
                    case 7777:
                    {
                        NSArray *temp = json[@"res"];
                        for (int i = 0; i < arrayUser.count; i++) {
                            NSString *status = temp[i][@"status"];
                            NSMutableDictionary *dict = arrayUser[i];
                            [dict setObject:status forKey:@"status"];
                            //[arrayUser[i] setValue:status forKey:@"status"];
                            
                            NSString* userid =temp[i][@"uid"];
                            [dict setObject:userid forKey:@"uid"];
                            
                            NSString* isfriend = temp[i][@"isfriends"];
                            [dict setObject:isfriend forKey:@"isfriends"];
                            
                        }
                    }
                        
                        break;
                        
                    case 7778:
                    {
                        
                        
                        UIAlertView* av = [[UIAlertView alloc]initWithTitle:@"添加好友成功" message:@"" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:Nil, nil];
                        [av show];
                        
                        [self matchContactWithStrMobile:_myStrMobile];
                        
                        
                        
//                        //change Cell for Row
//                        
//                        if (_cellIndex) {
//                            NSIndexPath *indexPath=[NSIndexPath indexPathForRow:_cellIndex inSection:0];
//                            [myTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
//                        }

                        
                    }
                        break;
                        
                }
                
                
                
            }
                
                
                
                
        }
    }
    [myTableView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [arrayUser count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60.0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
    if (nil == cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell1"];
        
        BeeUILabel *lb = [BeeUILabel spawn];
        lb.frame = CGRectMake(0, 0, 280, 60);
        lb.tag = 9527;
        lb.textAlignment = NSTextAlignmentRight;
        lb.textColor = [UIColor blackColor];
        [cell.contentView addSubview:lb];
    }
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.textLabel.text = arrayUser[indexPath.row][@"name"];
    cell.detailTextLabel.text = arrayUser[indexPath.row][@"phone"];
    
    BeeUILabel *lb = (BeeUILabel *)[cell viewWithTag:9527];
    
    NSString* cellText;
    
    if([arrayUser[indexPath.row][@"status"] boolValue] == 1){
        
        if ([arrayUser[indexPath.row][@"isfriends"] boolValue] == 0) {
            cellText = @"添加";
        }else{
            cellText = @"已添加";
        }
        
    }else{
        cellText = @"未安装";
    }
    
    lb.text = cellText;
    
   // lb.text = [arrayUser[indexPath.row][@"status"] boolValue]?@"添加":@"未安装";
    
    UIButton* addBtn = [[UIButton alloc]initWithFrame:CGRectMake(260, 0, 60, 60)];
    [addBtn setBackgroundColor:[UIColor clearColor]];
    addBtn.tag = indexPath.row;
    
    [addBtn addTarget:self action:@selector(addFrinds:) forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:addBtn];
    
    return cell;
}

- (void)addFrinds:(UIButton*)sender{
    
    NSString* fuid = [arrayUser[sender.tag] objectForKey:@"uid"];
    [self addFriendByFid:fuid];
    
    _cellIndex = sender.tag;

}

- (void)addFriendByFid:(NSString*)fuid{
    

    BeeHTTPRequest* req = [self POST:[NSString stringWithFormat:@"%@/apiuser/addfriend",kBaseUrl]].PARAM(@"fuid",fuid).PARAM(@"uid",kUserInfo[@"uid"]).PARAM(@"message",@"addFriend");
    req.tag = 7778;
    
    //[self POST:[NSString stringWithFormat:@"%@/apiuser/addfriend",kBaseUrl]].PARAM(@"uid",fuid).PARAM(@"fuid",kUserInfo[@"uid"]).PARAM(@"message",@"addFriend");
    
    
}






- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

@end
